package com.wanmait.server.config;

import com.wanmait.server.Shiro.UserRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;


/**
 * @ClassName ShiroConfig
 * @Author 蝶影
 * @Date 2020/12/820:50
 * @Version 1.0
 * 配置shiro信息
 **/

@Configuration
public class ShiroConfig {
    /**
     *@Author 蝶影
     *@Date 2020/12/8  20:56
     *@Version 1.0
     * 安全管理器，管理所的subject
    **/
    @Bean
    public SecurityManager securityManager(UserRealm userRealm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        securityManager.setRememberMeManager(null);
        return securityManager;
    }

    /**
     *@Author 蝶影
     *@Date 2020/12/8  20:57
     *@Version 1.0
     * shiro过滤链配置，当用户访问的界面需要登陆时，自动跳转到登陆界面
    **/
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilter=new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);

        //设定用户没有登录认证时的跳转链接、没有授权时的跳转链接
        shiroFilter.setLoginUrl("/login");
        shiroFilter.setUnauthorizedUrl("/");

        //过滤器链配置
        Map<String,String> filterMap = new LinkedHashMap();
        //访问以下数据时不需要登陆，可匿名访问
        filterMap.put("/statics/**","anon");
        filterMap.put("/login", "anon");
        filterMap.put("/loginVerification", "anon");
        filterMap.put("/favicon.ico", "anon");
        filterMap.put("/captcha.jpg", "anon");

//      filterMap.put("/swagger/**", "anon");
//      filterMap.put("/swagger-ui.html", "anon");
//      filterMap.put("/webjars/**", "anon");
//      filterMap.put("/swagger-resources/**", "anon");
        //除以上数据外，访问的其他界面，都需要登陆
        filterMap.put("/**","authc");

        shiroFilter.setFilterChainDefinitionMap(filterMap);
        return shiroFilter;
    }

    /**
     *@Author 蝶影
     *@Date 2020/12/8  21:15
     *@Version 1.0
     * 关于shiro的bean生命周期
    **/
    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor advisor=new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }


}
